<template>
  <div class="model-form">
    <el-page-header @back="goBack" content="更新商品">
    </el-page-header>
    <div class="model-content">
      <el-form ref="ruleForm" :rules="rules" :model="form" label-width="160px">
        <el-row :gutter="10">
          <el-col :span="13">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" name="name">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="13">
            <el-form-item label="商品主图" prop="logo">
              <avatar v-model="form.logo"></avatar>
            </el-form-item>

          </el-col>
          <el-col :span="13">
            <el-form-item label="商品分组" prop="productGroup">
              <el-tree-select ref="treeSelect" v-model="form.productGroup" :data="productGroupOptions" node-key="id"
                              check-strictly=true :render-after-expand="false"/>
            </el-form-item>

          </el-col>
          <el-col :span="13">
            <el-form-item label="库存" prop="stockNum">
              <el-input v-model="form.stockNum" name="stockNum">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="13">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" name="price">
              </el-input>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <el-form-item label="商品简介" prop="summary">
              <el-input v-model="form.summary" name="summary" type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="是否上架" prop="state">
              <el-switch v-model="form.state" :inactive-value="2" :active-value="1">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="是否开启规格" prop="skuEnable">
              <el-switch v-model="form.skuEnable">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="22" v-if="form.skuEnable">
            <template v-for="(item, index)  in specs" :key="item.key">
              <el-form-item size="mini" :label="'规格' + index">
                <div style="width: 100%;">
                  <el-input v-model="item.name" style="width: 500px;"></el-input>
                  <el-button @click.prevent="removeSpec(index)">删除</el-button>
                </div>
                <div style="margin:8px 5px">
                  <template v-for="(temp,j)  in item.values">
                    <div style="margin:6px 5px;display: inline-block;">
                      <el-input @change="updateSpecValue(index,j)" v-model="temp.name"
                                style="width: 200px;display: inline-block;">
                      </el-input>
                      <el-button @click.prevent="removeSpecValue(index,j)" type="danger"
                                 style="margin-right: 15px;">删除
                      </el-button>
                    </div>
                  </template>
                  <el-button @click.prevent="addSpecValue(index)">添加规格值</el-button>
                </div>

              </el-form-item>
            </template>
            <el-form-item label="" size="mini">
              <el-button @click.prevent="addSpec(index)" v-if="specs.length<2" type="primary">添加规格</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="22" v-if="form.skuEnable">
            <el-form-item label="规格详情" size="mini">
              <el-table v-loading="loading" :data="skus" style="width: 100%;font-size: 12px;">
                <el-table-column label="sku名称" prop="name" width="150">
                </el-table-column>
                <el-table-column label="原价" prop="price" sortable="custom" width="200">
                  <template #default="scope">
                    <el-input v-model="scope.row.price" size="mini" name="sortNum" :min="0"
                              :max="10000">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="销售价" prop="mealFee" width="200">
                  <template #default="scope">
                    <el-input v-model="scope.row.mealFee" size="mini" name="sortNum" :min="0"
                              :max="10000">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="库存" prop="stockNum" width="200">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.stockNum" size="mini" name="sortNum" :min="0"
                                     :max="10000">
                    </el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品介绍" prop="logo">
              <sc-editor v-model="form.note" placeholder="请输入" style="width: 100%;" :templates="templates"
                         :height="400"></sc-editor>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item>
              <el-button @click="goBack">取消</el-button>
              <el-button type="primary" @click="updateData">确定</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import common from "@/mixins/common.js";

import avatar from "@/components/avatar.vue";
import {defineAsyncComponent} from 'vue';

const scEditor = defineAsyncComponent(() => import('@/components/scEditor/index.vue'));
import {descartes} from "@/utils/descarteUtils";

export default {
  name: "product_update",
  mixins: [common],
  components: {
    avatar, scEditor
  },
  data() {
    return {
      form: {
        barCode: '',
        name: '',
        logo: '',
        productGroup: '',
        stockNum: '',
        price: '',
        summary: ''
      },
      specs: [],
      skus: [],
      productGroupOptions: [],
      rules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        productGroup: [
          {required: true, message: '请输入商品分组', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'}
        ],
      }
    }
  },
  async mounted() {
    await this.loadProductGroupOptions();

    let id = this.$route.query.id;
    let data = {};
    data.id = id;
    let res = await this.$http.post("/product/view", data);
    if (res.code === 200) {
      this.form = res.data;
      if (this.form.specs) {
        this.specs = this.form.specs;
      }
      if (this.form.skus) {
        this.skus = this.form.skus;
      }
    }
  },
  methods: {
    async updateData() {
      try {
        let valid = await this.$refs["ruleForm"].validate();
        if (!valid) {
          return;
        }
      } catch (e) {
        return;
      }
      await this.updateDataPost();
    },
    async updateDataPost() {

      this.form.specs = this.specs;
      this.form.skus = this.skus;

      let res = await this.$http.post("/product/update", this.form);
      if (res.code !== 200) {
        this.$message.error(res.msg);
        return
      }
      this.$message({
        message: '更新数据成功',
        type: 'success'
      });
      this.$router.go(-1);
    },
    async loadProductGroupOptions() {
      let self = this;
      let param = {};
      param.sortMethod = "asc";
      param.sortField = "id";
      param.level = 1;
      param.size = 500;
      param.fetch = 0;
      let res = await this.$http.post("/productGroup/list", param);
      if (res.code === 200) {
        self.productGroupOptions = res.data;
      }
    },
    addSpec() {

      this.specs.push({
        name: '',
        values: [],
        key: Date.now()
      });
    },
    removeSpec(index) {
      if (index > -1) {
        this.specs.splice(index, 1);
        this.updateSku();
      }
    },
    addSpecValue(item) {
      let temp = this.specs[item];
      if (temp.values == undefined || temp.values == null) {
        temp.values = [];
      }
      temp.values.push({name: ""});
      this.updateSku();
    },
    updateSku() {
      let specList = [];

      for (let index = 0; index < this.specs.length; index++) {
        const element = this.specs[index];
        console.info(JSON.stringify(element))
        if (element.values.length > 0) {
          specList.push(element.values);
        }
      }
      if (specList.length === 0) {
        this.skus = [];
        return;
      }
      let specResult = descartes(specList);
      let skus = [];
      for (let index = 0; index < specResult.length; index++) {
        console.info(specResult)
        let x = specResult[index].map(item => item.name);
        let element = x.join("_");
        let temp = {};
        temp.list = specResult[index];
        temp.price = "";
        temp.mealFee = "";
        temp.name = element;
        temp.stockNum = "";
        skus.push(temp);
      }
      this.skus = skus;
    },
    updateSpecValue(item, select) {
      let self = this;
      let temp = this.specs[item];
      let selectTemp = this.specs[item].values[select];
      if (select > -1) {
        for (let index = 0; index < temp.values.length; index++) {
          var element = temp.values[index];
          if (select !== index) {
            if (element.name === selectTemp.name) {
              self.$message.error("不能出现相同的规格值");
              selectTemp.name = "";
            }
          }

        }
      }
      this.updateSku();
    },
    removeSpecValue(item, index) {

      let temp = this.specs[item];
      if (index > -1) {
        temp.values.splice(index, 1)
      }
      this.updateSku();
    }
  }
}


</script>

<style scoped>

</style>
